// pages/accounts/detail/detail.js
const app = getApp();
var util = require('../../../utils/util.js');
let userinfo = app.globalData.userInfo;
const regeneratorRuntime = app.globalData.regeneratorRuntime;
const leadservice = require("../../../apiservice/lead/leadservice");
const screencustomerservice = require("../../../apiservice/screen/screencustomerservice");
const screenreservationserive = require("../../../apiservice/screen/screenreservationserive");
const screencallbackservice = require("../../../apiservice/screen/screencallbackservice");
const hospitalservice = require("../../../apiservice/hospital/hospitalservice");
const screenservice = require("../../../apiservice/screen/screenservice");
const reservationservice = require("../../../apiservice/reservation/reservationservice");

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		bookShow: false,
		leadDetail: {},
		screenCustomerData: {},
		rvationseriveData: {},
		screenCallData: {},
		screenResult: [],
		hospitalData: {},
		departmentData: {},
		screenItemData: {},
		hospitalIndex: 0,
		hospitalName: "爱尔眼科",
		departmentIndex: 0,
		departmentName: "请选择",
		screenItemIndex: 0,
		screenItemName: "请选择",
		screenIconName: "",
		reservationDate: util.addDateSeg(new Date().getTime(), "Month", 0, '-'),
		sreenAnchor: "",
		appointmentAnchor: "",
		visitAnchor: "",
		startReservationDate: util.addDateSeg(new Date().getTime(), "Month", 0, '-'),
		endReservationDate: util.addDateSeg(new Date().getTime(), "Month", 2, '-'),
		screenId: "",
    itemData: [
      { "id": 0, "name": "请选择" },
      { "id": 7, "name": "近视手术" }, 
      { "id": 3, "name": "高度近视" }, 
      { "id": 11, "name": "医学验光配镜" }, 
      { "id": 2, "name": "儿童眼病" },
      { "id": 8, "name": "斜弱视" },
      { "id": 5, "name": "角膜塑形镜" },
      { "id": 1, "name": "白内障" },
      { "id": 9, "name": "眼底病" },
      { "id": 4, "name": "角膜及眼表" },
      { "id": 10, "name": "眼整形眼眶病" },
      { "id": 12, "name": "青光眼" },
      { "id": 6, "name": "泪道病" },
      { "id": 14, "name": "角膜移植" },
      { "id": 15, "name": "青光VIP特需门诊眼" },
      { "id": 13, "name": "其他" }
    ],
    itemindex:0,
    description:""
	},


	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function(options) {
		console.log(this.data.startReservationDate);
		console.log(this.data.endReservationDate);
		console.log(options.leadId);
		console.log(options.screenId);
	
		wx.showLoading({
			title: '加载中...',
			mask: true
		});
		try {
			await this.GetAcountDetailsData(options.leadId);
			await this.GetScreenCustomerByLeadId(options.leadId);
			await this.QueryReservationByLeadId(options.leadId);
			await this.GetScreenCallBackByLeadId(options.leadId);
			await this.GetAccountScreenDetailData(options.leadId, options.screenId);
			await this.GetScreenItemData(options.leadId);
			await this.GetHospital();
		} catch (e) {
			//TODO handle the exception
			console.error(e);
		} finally {
			wx.hideLoading();
		}

	},
	
	toScreenInfo:function(e){
		let screenid = e.currentTarget.dataset.id;
		wx.navigateTo({
			url:`/pages/screens/info/info?screenId=${screenid}`
		})
	},

	//根据leadId获取客户详细信息
	async GetAcountDetailsData(leadId) {
		try {
			if (leadId != null) {
				var leadDetailData = await leadservice.GetAcountDetailsData(leadId);
				console.log(leadDetailData);
				if (leadDetailData) {
					this.setData({
						leadDetail: leadDetailData.data
					});
				}
			}
		} catch (e) {
			throw e;
			console.log(e);
		} finally {
			//wx.hideLoading();
		}
	},

	//根据潜客Id获取筛查客户信息
	async GetScreenCustomerByLeadId(leadId) {
		try {
			if (leadId != null) {
				var screenCustomerResult = await screencustomerservice.GetScreenCustomerByLeadId(leadId);
				console.log(screenCustomerResult.data);
				if (screenCustomerResult) {
					this.setData({
						screenCustomerData: screenCustomerResult.data
					});
				}
			}
		} catch (e) {
			throw e;
			console.log(e);
		} finally {
			//wx.hideLoading();
		}
	},

	//根据潜客Id获取预约信息
	async QueryReservationByLeadId(leadId) {
		try {
			if (leadId != null) {
				var rvationseriveResult = await screenreservationserive.QueryReservationListByLeadId(leadId, true);
				if (rvationseriveResult) {
					this.setData({
						rvationseriveData: rvationseriveResult.data
					});
				}
			}
		} catch (e) {
			throw e;
			console.log(e);
		} finally {
			//wx.hideLoading();
		}
	},

	//根据潜客Id获取筛查结果
	async GetAccountScreenDetailData(leadId, screenId) {
		try {
			
			if (leadId != null && screenId != null) {
				var screenResult = await leadservice.GetAccountScreenDetailData(leadId, screenId);
				if (screenResult) {
					debugger;
					this.setData({
						screenResult: screenResult.data
					});
				}
			}
		} catch (e) {
			throw e;
			console.log(e);
		} finally {
			//wx.hideLoading();
		}
	},

	//根据潜客Id获取筛查回访信息
	async GetScreenCallBackByLeadId(leadId) {
		try {
			if (leadId != null) {
				var screencallResult = await screencallbackservice.GetScreenCallBackByLeadId(leadId, true);

				if (screencallResult) {
					this.setData({
						screenCallData: screencallResult.data
					});
				}
			}
		} catch (e) {
			throw e;
			console.log(e);
		} finally {
			//wx.hideLoading();
		}
	},

	//获取所有医院
	async GetHospital() {
		try {
			let userInfo = app.globalData.userInfo;
			var HospitalData = await hospitalservice.GetHospital();

      var hospitalindex = this.getPickerValue(HospitalData.data, userInfo.siteid);
			if (HospitalData.data && hospitalindex) {
				this.setData({
					hospitalIndex: hospitalindex,
					hospitalData: HospitalData.data,
					hospitalName: HospitalData.data[hospitalindex].name,
				});
			}
			await this.GetDepartmentData(HospitalData.data[hospitalindex].siteId);
		} catch (e) {
			throw e;
			console.log(e);
		} finally {
			//wx.hideLoading();
		}
	},
	getPickerValue: function(targetObj, id) {
		for (let index in targetObj) {
      if (targetObj[index].siteId == id) {
				return index
			}
		}
	},

  changeItem:function(e){
    this.setData({itemindex:e.detail.value})
  },

	//根据医院Id获取科室信息
	async GetDepartmentData(hospitalId) {
		try {
			if (hospitalId) {
				var DepartmentData = await hospitalservice.GetDepartmentByHospitalId(hospitalId);
				console.log(DepartmentData.data);
				if (DepartmentData) {
					this.setData({
						departmentData: DepartmentData.data,
					});
          if(this.data.departmentIndex!=0){
            this.setData({
              departmentName: DepartmentData.data[this.data.departmentIndex].departmentName,
            });
          }
				}
			}
		} catch (e) {
			throw e;
			console.log(e);
		} finally {
			//wx.hideLoading();
		}
	},

	//根据leadId获取筛查项目信息
	async GetScreenItemData(leadId) {
		try {
			if (leadId) {
				var ScreenItemData = await screenservice.GetScreenItemData(leadId);
				if (ScreenItemData && ScreenItemData.data.length > 0) {
					this.setData({
						screenItemData: ScreenItemData.data,
						screenItemName: ScreenItemData.data[this.data.screenItemIndex].new_new_screenitemName,
					});
				}
			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},


	//预约时间发生改变时
	changeDate: function(e) {
		console.log(e);
		this.setData({
			reservationDate: e.detail.value
		});
	},

	//医院发生改变时
	changeHospital: async function(e) {
		console.log(e);
		if (this.data.hospitalData && this.data.hospitalData.length > 0) {
			debugger
			var hospitalId = this.data.hospitalData[e.detail.value].siteId;
			var hospitalName = this.data.hospitalData[e.detail.value].name;
			this.setData({
				hospitalIndex: e.detail.value,
				hospitalName: hospitalName
			});
			await this.GetDepartmentData(hospitalId);
		}
	},

	//科室发生改变时
	changeDepartment: function(e) {
		if (this.data.departmentData && this.data.departmentData.length > 0) {
			this.setData({
				departmentIndex: e.detail.value,
				departmentName: this.data.departmentData[e.detail.value].departmentName
			});
		}
	},

	//筛查项目改变时
	changeScreenItem: function(e) {
		if (this.data.screenItemData && this.data.screenItemData.length > 0) {
			var screenItemName = this.data.screenItemData[e.detail.value].new_new_screenitemName;
			this.setData({
				screenItemIndex: e.detail.value,
				screenItemName: screenItemName
			});
		}
	},
  changedescription:function(e){
    this.setData({description:e.detail});
  },
	toAnchor: function(e) {
		if (e.currentTarget.id == "sreenAnchor") {
			wx.createSelectorQuery()
				.select("#sreenCollapse")
				.boundingClientRect(function(rect) {
					wx.pageScrollTo({
						scrollTop: rect.bottom,
						duration: 0
					});
				})
				.exec();
			this.setData({
				sreenAnchor: "anchor-item--active",
				appointmentAnchor: "",
				visitAnchor: "",
			})

		} else if (e.currentTarget.id == "appointmentAnchor") {
			wx.createSelectorQuery()
				.select("#appointmentCollapse")
				.boundingClientRect(function(rect) {
					wx.pageScrollTo({
						scrollTop: rect.bottom,
						duration: 0
					});
				})
				.exec();
			this.setData({
				sreenAnchor: "",
				appointmentAnchor: "anchor-item--active",
				visitAnchor: "",
			})

		} else if (e.currentTarget.id == "visitAnchor") {
			wx.createSelectorQuery()
				.select("#visitCollapse")
				.boundingClientRect(function(rect) {
					wx.pageScrollTo({
						scrollTop: rect.bottom,
						duration: 0
					});
				})
				.exec();
			this.setData({
				sreenAnchor: "",
				appointmentAnchor: "",
				visitAnchor: "anchor-item--active",
			})
		}
	},

	//保存
	onSave: async function(e) {
    if(this.data.itemindex==0){
      wx.showToast({
        title: '项目不能为空',
        duration:1500,
        icon:'none'
      })
      return;
    }
		await this.CreaterReservation();
	},

	//创建预约信息
	async CreaterReservation() {
		wx.showLoading({
			title: '保存中...',
			mask: true
		});
		try {
			var Reservation = {};
      Reservation.new_remark = this.data.description;
			Reservation.new_mobile = this.data.leadDetail.phone;
			Reservation.new_lead = this.data.leadDetail.leadId;
			Reservation.new_age = this.data.leadDetail.new_age;
			Reservation.new_reservationdate = this.data.reservationDate;
			Reservation.new_hospital = this.data.hospitalData[this.data.hospitalIndex].siteId;
      if(this.data.departmentIndex!=0)
			  Reservation.new_department = this.data.departmentData[this.data.departmentIndex].new_departmentId;
      Reservation.new_contnt = this.data.itemData[this.data.itemindex].id;
      if (this.data.screenItemData && this.data.screenItemData.length > 0){
        Reservation.new_new_screenitem = this.data.screenItemData[this.data.screenItemIndex].new_new_screenitem;
      }
			var result = await reservationservice.CreaterReservation(Reservation);

			await this.QueryReservationByLeadId(this.data.leadDetail.leadId);
			console.log(result);
			this.onClose();
			wx.hideLoading();
			wx.showModal({
				title: '提示',
				showCancel: false,
				content: '保存成功',
			})
		} catch (e) {
			wx.hideLoading();
			console.log(e);
		}
	},

	addBook() {
		this.setData({
			bookShow: true
		})
	},

	onClose() {
		this.setData({
			bookShow: false
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
  callPhone: function (event) {
    if (this.data.leadDetail.phone) {
      var phone = this.data.leadDetail.phone;
      wx.makePhoneCall({
        phoneNumber: phone,
      });
    }
  },
})
